import { XDomain } from "@/ts/base/schema";
import { StyleVarDefinition, styleVarDefs } from ".";
import _ from "lodash";
import { IDisposable } from "@/ts/base/common";


type StyleVarGroup = Record<StyleVarDefinition["group"], Dictionary<string>>;


export default class Theme implements IDisposable {
  readonly domainSetting?: XDomain;

  private groupedStyleVars: StyleVarGroup = {
    style: {},
    file: {},
    config: {},
    icon: {},
  };

  /** 登录页系统标题 */
  get systemTitle() {
    return this.groupedStyleVars.config.systemTitle;
  }
  get loginBackground() {
    return this.groupedStyleVars.file.loginBackground;
  }
  
  get organizerName() {
    return this.groupedStyleVars.config.organizerName;
  }
  get organizerLink() {
    return this.groupedStyleVars.config.organizerLink;
  }
  

  private style?: HTMLStyleElement;
  constructor(domainSetting: XDomain | undefined) {
    this.domainSetting = domainSetting;
  }
  dispose(): void {
    if (this.style) {
      this.style.remove();
    }
  }

  init() {
    if (!this.domainSetting) {
      return;
    }
    const styleVars = this.domainSetting.theme?.styleVars ?? {};
    for (const def of styleVarDefs) {
      var value = styleVars[def.name];
      if (value != null) {
        this.groupedStyleVars[def.group][def.name] = value;
      }
    }
  }

  /**
   * 加载样式变量
   */
  loadCssVars() { 
    if (!this.style) {
      this.style = document.createElement("style");
      document.head.appendChild(this.style);
    }

    const vars = Object.entries(this.groupedStyleVars.style)
      .map(([key, value]) => `${key}: ${value};`)
      .join('\n');
    this.style.innerHTML = `:root {\n${vars}\n}`;
  }
}